package com.zzx.boot.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.stereotype.Controller;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全部异常处理类
 */
//添加异常处理类
    //处理在类上修饰了RestController和Controller注解的类
@ControllerAdvice(annotations ={ RestController.class,Controller.class})
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 处理异常的方法
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(Exception e){
        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[9]+"已存在!";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException customException){


        return R.error(customException.getMessage());
    }
}
